package secondkill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import secondkill.mapper.TSeckillOrderMapper;
import secondkill.pojo.TSeckillOrder;
import secondkill.pojo.TUser;
import secondkill.service.ITSeckillOrderService;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Dzy
 * @since 2022-01-19
 */
@Slf4j
@Service
public class TSeckillOrderServiceImpl extends ServiceImpl<TSeckillOrderMapper, TSeckillOrder> implements ITSeckillOrderService {


    @Autowired
    private TSeckillOrderMapper seckillOrderMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取抢购结果
     * return  orderId:成功 -1 秒杀失败，  0 排队中
     * @param user
     * @param goodsId
     * @return
     */
    @Override
    public Long getResult(TUser user, Long goodsId) {

        TSeckillOrder secKillOrder = seckillOrderMapper.selectOne(new QueryWrapper<TSeckillOrder>().eq("user_id", user.getId()).eq("goods_id", goodsId));
        log.info(">>>>>>>>>>>secKillOrder:{}",secKillOrder);
        if (null != secKillOrder) {
            return secKillOrder.getOrderId();
        } else if (redisTemplate.hasKey("isStockEmpty:" + goodsId)) {
            return -1L;
        } else {
            return 0L;
        }
    }
}
